//
//  SSCommentViewController.swift
//  Alamofire
//
//  Created by 松松 on 2019/4/12.
//

import UIKit
import SSBaseTool
import SSExtensions
import SSComment
import SSIconFont

open class SSCommentViewController: UIViewController {


    private lazy var pageVC = { () -> UIPageViewController in 
        let pageVc = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
        pageVc.delegate = self
        pageVc.dataSource = self
        addChildViewController(pageVc)

        return pageVc
    }()
    private lazy var headTitleView = { () -> UIView in
        let headerView = UIView(frame: CGRect(x: 0, y: STATUES_HEIGHT + 44, width: SCREEN_WIDTH, height: 44))
        headerView.backgroundColor = UIColor(hexString: colorModel.bgColor)

        return headerView
    }()

    private lazy var allCommentsButton = { () -> UIButton in
        let button = UIButton(frame: CGRect.zero)
        button.setTitle("全部评论", for: .normal)
        button.setTitleColor(UIColor(hexString: colorModel.labelNormalColor), for: .normal)
        button.setTitleColor(UIColor(hexString: colorModel.labelSelectedColor), for: .selected)

        return button
    }()

    private lazy var authorReplayButton = { () -> UIButton in
        let button = UIButton(frame: CGRect.zero)
        button.setTitle("作者回复", for: .normal)
        button.setTitleColor(UIColor(hexString: colorModel.labelNormalColor), for: .normal)
        button.setTitleColor(UIColor(hexString: colorModel.labelSelectedColor), for: .selected)

        return button
    }()

    private lazy var lineScrollView = { () -> UIScrollView in
        let scrollView = UIScrollView(frame: CGRect.zero)
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.isScrollEnabled = false
        scrollView.contentSize = CGSize(width: SCREEN_WIDTH*2, height: 3)
        scrollView.contentOffset = CGPoint(x: SCREEN_WIDTH, y: 0)
        return scrollView
    }()

    private lazy var lineView = { () -> UIView in
        let line = UIView(frame: CGRect.zero)
        line.backgroundColor = UIColor(hexString: colorModel.labelSelectedColor)

        return line
    }()

    private lazy var commentButton = { () -> UIButton in
        let button = UIButton(frame: CGRect.zero)
        button.setFontTitle(text: SSIconText.ico_commente625.rawValue, size: 30, state: .normal)
        button.backgroundColor = UIColor(hexString: colorModel.iconBGColor)
        button.cornerRadius = 25
        button.setTitleColor(UIColor(hexString: colorModel.iconColor), for: .normal)
        button.addShadow(color: UIColor.darkGray, offset: CGSize(width: 3, height: 3), alpha: 0.7, radius: 3)
        return button
    }()

    private lazy var likeButton = { () -> UIButton in
        let button = UIButton(frame: CGRect.zero)
        button.setFontTitle(text: SSIconText.ico_goode626.rawValue, size: 30, state: .normal)
        button.backgroundColor = UIColor(hexString: colorModel.iconBGColor)
        button.cornerRadius = 25
        button.setTitleColor(UIColor(hexString: colorModel.iconColor), for: .normal)
        button.addShadow(color: UIColor.darkGray, offset: CGSize(width: 3, height: 3), alpha: 0.7, radius: 3)
        return button
    }()

    private lazy var collectButton = { () -> UIButton in
        let button = UIButton(frame: CGRect.zero)
        button.setFontTitle(text: SSIconText.ico_star1e627.rawValue, size: 30, state: .normal)
        button.backgroundColor = UIColor(hexString: colorModel.iconBGColor)
        button.cornerRadius = 25
        button.setTitleColor(UIColor(hexString: colorModel.iconColor), for: .normal)
        button.addShadow(color: UIColor.darkGray, offset: CGSize(width: 3, height: 3), alpha: 0.7, radius: 3)
        return button
    }()

    private lazy var shareButton = { () -> UIButton in
        let button = UIButton(frame: CGRect.zero)
        button.setFontTitle(text: SSIconText.ico_sharee62a.rawValue, size: 30, state: .normal)
        button.backgroundColor = UIColor(hexString: colorModel.iconBGColor)
        button.cornerRadius = 25
        button.setTitleColor(UIColor(hexString: colorModel.iconColor), for: .normal)
        button.addShadow(color: UIColor.darkGray, offset: CGSize(width: 3, height: 3), alpha: 0.7, radius: 3)
        return button
    }()

    private var VCs = [UIViewController]()
    private var currentIndex = 0
    private var scrollView : UIScrollView!
    private var estimateOffSetX: CGFloat = 0
    private let commentVM = SSCommentViewModel()
    var colorModel = SSCommentColorModel()

    

    override open func viewDidLoad() {
        super.viewDidLoad()
        title = "全部评论"
        //设置标题颜色
        let titleColor = UIColor(hexString: colorModel.titleColor)
        self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor : titleColor,NSAttributedStringKey.font : UIFont.systemFont(ofSize: 18)]
//        self.navBarTintColor = titleColor
//        self.navigationController?.navigationBar.isTranslucent = false
        let bgColor = UIColor(hexString: colorModel.bgColor)
        self.navigationController?.navigationBar.barTintColor = bgColor
        self.navigationController?.navigationBar.backgroundColor = bgColor
        setUI()
        getData()
        setEvent()
    }


    //MARK:设置UI
    private func setUI(){
        view.backgroundColor = UIColor(hexString: colorModel.bgColor)
        allCommentsButton.frame = CGRect(x: 0, y: 0, width: 90, height: 40)
        
        authorReplayButton.frame = CGRect(x: allCommentsButton.frame.width, y: 0, width: allCommentsButton.frame.width, height: allCommentsButton.frame.height)

        lineScrollView.frame = CGRect(x: 0, y: 41, width: SCREEN_WIDTH, height: 3)

        lineView.frame = CGRect(x: SCREEN_WIDTH, y: 0, width: allCommentsButton.frame.width, height: 3)

        let width : CGFloat = 50
        commentButton.frame = CGRect(x: 40, y: SCREEN_HEIGHT - STATUES_HEIGHT - BOTTOM_SAFE_HEIGHT - 80, width: width, height: width)
        shareButton.frame = CGRect(x: SCREEN_WIDTH - 70, y: 0, width: width, height: width)
        shareButton.centerY = commentButton.centerY

        collectButton.frame = CGRect(x: shareButton.x - width - 15, y: 0, width: width, height: width)
        collectButton.centerY = shareButton.centerY

        likeButton.frame = CGRect(x: collectButton.x - width - 15, y: 0, width: width, height: width)
        likeButton.centerY = shareButton.centerY

        headTitleView.addSubview(allCommentsButton)
        headTitleView.addSubview(authorReplayButton)
        headTitleView.addSubview(lineScrollView)
        lineScrollView.addSubview(lineView)
//        view.addSubview(headTitleView)
        view.addSubview(pageVC.view)
        view.addSubview(commentButton)
//        view.addSubview(shareButton)
//        view.addSubview(likeButton)
//        view.addSubview(collectButton)

        pageVC.view.frame = CGRect(x: 0, y: STATUES_HEIGHT + 44, width: SCREEN_WIDTH, height: SCREEN_HEIGHT - STATUES_HEIGHT - 44.0 - BOTTOM_SAFE_HEIGHT)

        let subViews = pageVC.view.ts_allSubviews()
        for view in subViews{
            if view.isKind(of: UIScrollView.self){
                self.scrollView = view as? UIScrollView
                break
            }
        }
        scrollView.delegate = self
    }

    //MARK:获取数据
    private func getData(){
        let vc1 = AllCommentsViewController()
        vc1.colorModel = colorModel

        let vc2 = AuthorReplayViewController()
        vc2.colorModel = colorModel

        VCs = [vc1]
        pageVC.setViewControllers([VCs[0]], direction: .forward, animated: false, completion: nil)
        allCommentsButton.isSelected = true

//        commentVM.checkIsLike(appCode: APP_CODE, toItemCode: userModel.toItemCode!, mainTypeCode: userModel.mainTypeCode!, formUserId: userModel.fromUserId!, success: { (modelData) in
//            self.likeButton.isSelected = modelData.obj
//        }) { (err) in
//
//        }

    }

    //MARK:设置事件
    private func setEvent(){
        //所有评论
        allCommentsButton.addClick { (sender) in
            if sender.isSelected {return}
            sender.isSelected = true
            self.authorReplayButton.isSelected = false

            self.lineScrollView.setContentOffset(CGPoint(x: SCREEN_WIDTH, y: 0), animated: true)
            self.pageVC.setViewControllers([self.VCs[0]], direction: .reverse, animated: true, completion: { (success) in

            })
        }
        //作者回复
        authorReplayButton.addClick { (sender) in
            if sender.isSelected {return}
            sender.isSelected = true
            self.allCommentsButton.isSelected = false
            let offset = CGPoint(x:SCREEN_WIDTH - self.allCommentsButton.frame.width, y: 0)
            self.lineScrollView.setContentOffset(offset, animated: true)
            self.pageVC.setViewControllers([self.VCs[1]], direction: .forward, animated: true, completion: { (success) in

            })
        }

        //评论点击事件
        commentButton.addTarget(self, action: #selector(comment(_:)), for: .touchUpInside)
        //点赞点击事件
        likeButton.addTarget(self, action: #selector(like(_:)), for: .touchUpInside)

    }

    //MARK:点赞
    @objc
    private func like(_ sender: UIButton){

        sender.isUserInteractionEnabled = false
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
            sender.isUserInteractionEnabled = true
        }
        if userModel.fromUserId == nil{
            unowned let weakSelf = self
            commentLoginBlock?(weakSelf)
            return
        }
        if sender.isSelected{//取消点赞
            commentVM.cancelLike(appCode: APP_CODE, toItemCode: userModel.toItemCode!, mainTypeCode: userModel.mainTypeCode!, formUserId: userModel.fromUserId!, success: { (model) in
                sender.isSelected = false
            }) { (err) in

            }
        }else{//点赞
            commentVM.like(appCode: APP_CODE, fromUserName: userModel.fromUserName!, fromUserHead: userModel.fromUserHead!, toItemCode: userModel.toItemCode!, goodType: 1, mainTypeCode: userModel.mainTypeCode!, formUserId: userModel.fromUserId!, success: { (modelData) in
                sender.isSelected = true
            }) { (err) in

            }
        }
    }

    //MARK:评论当前内容
    @objc
    private func comment(_ sender: UIButton){
        if userModel.fromUserId == nil{
            unowned let weakSelf = self
            commentLoginBlock?(weakSelf)
            return
        }
        let vc = CommentTextFieldViewController(placeholder: "请输入评论内容...", placeholderColor: UIColor.lightGray, maxLength: COMMENT_MAX_CONTENT) { (text) in
            self.commentVM.addComment(appCode: APP_CODE, fromUserName: userModel.fromUserName!, fromUserHead: userModel.fromUserHead!, formUserId: userModel.fromUserId!, commentImages: nil, replyCommentId: nil, commentId: nil, mainTypeCode: userModel.mainTypeCode!, toItemCode: userModel.toItemCode!, commentContent: text, success: { (modelData) in
                (self.VCs[0] as! AllCommentsViewController).addComment(modelData)

            }, error: { (error) in

            })
        }
        self.present(vc, animated: true, completion: nil)
    }
}

extension SSCommentViewController : UIPageViewControllerDelegate,UIPageViewControllerDataSource{
    public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
        var index = VCs.firstIndex(of: viewController)
        if index == nil || index == 0{
            return nil
        }
        index! -= 1
        return VCs[index!]

    }

    public func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
        var index = VCs.firstIndex(of: viewController)
        if index == nil || index == VCs.count - 1{
            return nil
        }
        index! += 1
        return VCs[index!]
    }

    public func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) {
        let vc = pendingViewControllers.first!
        let index = VCs.firstIndex(of: vc)
        currentIndex = index ?? 0
    }

    public func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {

        if completed{
            if currentIndex == 0{
                self.allCommentsButton.isSelected = true
                self.authorReplayButton.isSelected = false

                self.lineScrollView.setContentOffset(CGPoint(x: SCREEN_WIDTH, y: 0), animated: true)
            }else{
                self.authorReplayButton.isSelected = true
                self.allCommentsButton.isSelected = false
                let offset = CGPoint(x:SCREEN_WIDTH - self.allCommentsButton.frame.width, y: 0)
                self.lineScrollView.setContentOffset(offset, animated: true)
            }
        }

    }
    

}


extension SSCommentViewController : UIScrollViewDelegate{
    public func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let pageWidth = view.frame.width
        for vc in VCs{
            let p = vc.view.convert(CGPoint(), to: view)
            //找出屏幕可视范围的控制器视图
            if (p.x) > CGFloat(0.0) && (p.x) < pageWidth{
                let estimatePage = (VCs.index(of: vc))!
                estimateOffSetX = CGFloat(estimatePage) * pageWidth - (p.x)
            }
        }
        //若不是循环，最后一个找不到左边距
        if estimateOffSetX >= CGFloat((VCs.count)-1)*pageWidth{
            let p = VCs[(VCs.count)-1].view.convert(CGPoint(), to: view)
            estimateOffSetX = CGFloat((VCs.count)-1) * pageWidth - (p.x)
        }
        lineScrollView.contentOffset = CGPoint(x:SCREEN_WIDTH - estimateOffSetX/view.frame.width*allCommentsButton.frame.width, y: 0)

    }
    private func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let pageWidth = view.frame.width
        currentIndex = Int(round(estimateOffSetX/pageWidth))
        if currentIndex < 0 {
            currentIndex = (VCs.count) - 1
        }
        estimateOffSetX = CGFloat(currentIndex)*pageWidth

        lineScrollView.contentOffset = CGPoint(x:SCREEN_WIDTH - estimateOffSetX/view.frame.width*allCommentsButton.frame.width, y: 0)
    }
}
